package net.simflow.swf.analyzer.network.opt;

import java.net.URI;

import uk.org.taverna.scufl2.api.configurations.Configuration;
import uk.org.taverna.scufl2.api.port.InputProcessorPort;
import uk.org.taverna.scufl2.api.port.InputWorkflowPort;
import uk.org.taverna.scufl2.api.port.OutputProcessorPort;
import uk.org.taverna.scufl2.api.port.OutputWorkflowPort;
import uk.org.taverna.scufl2.api.property.PropertyReference;

public class PortNameMaker {

	private static PortNameMaker instance = new PortNameMaker();

	private PortNameMaker() {
	}

	public static PortNameMaker getInstance() {
		return instance;
	}

	public String make(InputWorkflowPort port) {
		return (port != null) ? port.getParent().getName() + ": "
				+ port.getName() : null;
	}

	public String make(OutputWorkflowPort port) {
		return (port != null) ? port.getParent().getName() + ": "
				+ port.getName() : null;
	}

	public String make(Configuration config, OutputProcessorPort port) {
		if (config == null || port == null) {
			return null;
		}
		try {
			String workflowName = makeWorkflowName(config);
			String portName = port.getName();
			return (workflowName != null & portName != null) ? workflowName
					+ ": " + portName : null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public String make(Configuration config, InputProcessorPort port) {
		if (config == null || port == null) {
			return null;
		}
		try {
			String workflowName = makeWorkflowName(config);
			String portName = port.getName();
			return (workflowName != null & portName != null) ? workflowName
					+ ": " + portName : null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public String makeWorkflowName(Configuration config) {
		if (config == null) {
			return null;
		}
		try {
			String workflowName = null;
			for (PropertyReference pr : config
					.getPropertyResource()
					.getPropertiesAsReferences(
							new URI(
									"http://ns.taverna.org.uk/2010/activity/nested-workflow#workflow"))) {
				URI wn = pr.getResourceURI();
				if (wn != null) {
					StringBuffer str = new StringBuffer();
					str.append(wn.getPath()).deleteCharAt(str.length() - 1)
							.delete(0, str.lastIndexOf("/") + 1);
					workflowName = str.toString();
					continue;
				}
			}
			return workflowName;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
